package commonAdmin.dao;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ConnectionCallback;
import org.springframework.stereotype.Repository;

import commonAdmin.domain.Game;
import commonAdmin.domain.Page;
import commonAdmin.domain.WebPageSearchCondition;
import commonAdmin.sql.support.SqlStatmentWithArgs;

@Repository
public class GameDaoMysqlImpl extends BaseDaoImpl<Game, Long> implements GameDao {

	@Override
	protected SqlStatmentWithArgs buildPageQueryConditionStatement(WebPageSearchCondition<Game> searchCondition, Page<Game> page) {
		StringBuilder conditionStatement = new StringBuilder();
		List<Object> args = new ArrayList<Object>();

		conditionStatement.append(" where 1=1 ");
		Game game = searchCondition.getModel();
		if (game.getId() != null) {
			conditionStatement.append(" and id=?");
			args.add(game.getId());
		}
		if (StringUtils.isNotBlank(game.getName())) {
			conditionStatement.append(" and name=?");
			args.add(game.getName());
		}

		return new SqlStatmentWithArgs(conditionStatement.toString(), args);
	}

	public void getTableMetaData(String tableName) {
		jdbcTemplate.execute(new ConnectionCallback<Object>() {

			@Override
			public Object doInConnection(Connection con) throws SQLException, DataAccessException {
				DatabaseMetaData dbmd = con.getMetaData();
				ResultSet colRet = dbmd.getColumns(null, "%", tableName, "%");
				while (colRet.next()) {
					//http://blog.csdn.net/zoucui/article/details/6125522
					String columnName = colRet.getString("COLUMN_NAME");
					String columnType = colRet.getString("TYPE_NAME");
					int datasize = colRet.getInt("COLUMN_SIZE");
					int digits = colRet.getInt("DECIMAL_DIGITS");
					int nullable = colRet.getInt("NULLABLE");
					System.out.println(columnName + " " + columnType + " " + datasize + " " + digits + " " + nullable);
				}
				return null;
			}
		});
	}

}
